<template>
  <el-dialog v-el-drag-dialog title="选择角色" :visible.sync="visible" :append-to-body="appendToBody">
    <el-card class="m-l-5">
      <el-input v-model="filterRoleText" class="m-b-10" placeholder="搜索角色" />

      <el-tree
        ref="roleTreeDialog"
        node-key="id"
        :data="roleData"
        :props="roleProps"
        :filter-node-method="filterRoleNode"
        class="filter-tree"
        show-checkbox
        :default-expand-all="expandAll"
        highlight-current
        check-on-click-node
        :check-strictly="single"
        @check-change="handleClick"
      />
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { roleTreeData } from '@/api/system/role'

export default {
  name: 'RoleTreeDialog',
  props: {
    appendToBody: {
      type: Boolean,
      default: true
    },
    expandAll: {
      type: Boolean,
      default: true
    },
    single: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      filterRoleText: '',
      roleData: [],
      roleProps: {
        children: 'children',
        label: 'name'
      },
      number: 0,
      selected: []
    }
  },
  watch: {
    filterRoleText(val) {
      this.$refs.roleTreeDialog.filter(val)
    }
  },
  methods: {
    init(selected) {
      this.visible = true
      this.selected = selected
      this.$nextTick(() => {
        this.getTreeData()
      })
    },
    getTreeData() {
      roleTreeData({}).then(response => {
        this.roleData = response
        if (this.selected) {
          const selectedNode = this.selected.length > 0 ? this.selected.split(',') : [this.selected]
          this.$refs.roleTreeDialog.setCheckedKeys(selectedNode)
          if (this.single) {
            this.number = 1
          }
        }
      }).catch(e => {})
    },
    filterRoleNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleClick(data, checked, node) {
      if (this.single) {
        this.number++
        if (this.number % 2 === 0) {
          if (checked) {
            this.$refs.roleTreeDialog.setCheckedNodes([])
            this.$refs.roleTreeDialog.setCheckedNodes([data])
          } else {
            this.$refs.roleTreeDialog.setCheckedNodes([])
          }
        }
      }
    },
    onSubmit() {
      const checked = this.$refs.roleTreeDialog.getCheckedNodes()
      if (this.single && checked.length === 0) {
        this.$modal.msgWarning('请至少选择一项')
        return
      }
      this.$emit('confirmDialog', checked)
      this.visible = false
    }
  }
}
</script>
